package com.dxysun.springboot.aop;

import com.alibaba.fastjson.JSON;
import com.dxysun.springboot.dto.User;
import com.dxysun.springboot.reslover.UserParamResolver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Aspect
@Order(1)
public class ControllerAspect
{
    private static final Log logger = LogFactory.getLog(ControllerAspect.class);

    @Around("execution(* com.dxysun.springboot.controller.aop..*.*(..)) && @annotation(org.springframework.web.bind.annotation.ResponseBody)")
    public Object process(ProceedingJoinPoint pjp) throws Throwable
    {
        HttpServletRequest request = null;
        HttpServletResponse response = null;
        User user = null;
        Object[] args = pjp.getArgs();
        for (Object arg : args)
        {
            if (arg instanceof User)
            {
                user = (User) arg;
            }
            else if (arg instanceof HttpServletRequest)
            {
                request = (HttpServletRequest) arg;
            }
            else if (arg instanceof HttpServletResponse)
            {
                response = (HttpServletResponse) arg;
            }
        }
        if(user != null)
        {
            user.setGender("male");
            logger.info("in aspect:" + JSON.toJSONString(user));
        }
        Object object;
        try {
            object = pjp.proceed();
        }
        catch (Exception e)
        {
            logger.error("aop error", e);
            object = new User("error");
        }
        return object;
    }
}
